import { defineStore } from "pinia"
// 导入基地址
import request from '@/utils/request'
// 导入类型
import {IResponse} from '@/types/data'
import {CategoryItem,TopCategory,SubCategory} from '@/types/good'
// 导入常量
import { topCategory } from '../constants'
const defaultCategory = topCategory.map((item) => ({
  name: item,
}))

// 创建category模块
export default defineStore('category',{
  state:() => ({
    list:defaultCategory as CategoryItem[],
    // 面包屑
    topCategory: {} as TopCategory,
    // 二级类目
    subCategory: {} as SubCategory,
  }),
  actions:{
    // 获取导航列表
    async getAllCategory() {
      const res = await request.get<IResponse<CategoryItem[]>>('/home/category/head')
      // 给后端返回的数据统一添加open属性  用于控制子分类的显示隐藏
      res.data.result.forEach((item) => (item.open = false))
      this.list = res.data.result
      console.log('getAllCategory',res)
    },
    // show hide 方法控制显示和隐藏
    show(categoryId: string) {
      this.list.find((item) => item.id === categoryId)!.open = true
    },
    hide(categoryId: string) {
      this.list.find((item) => item.id === categoryId)!.open = false
    },
    // 根据一级分类id 获取详情
    async getTopCategory(id: string) {
      const res = await request.get<IResponse<TopCategory>>('/category', {
          params: {id}
      })
      this.topCategory = res.data.result
    },
    // 
    async getSubFilter(id: string) {
      const res = await request.get<IResponse<SubCategory>>('/category/sub/filter', {
          params: {
              id,
          },
      })
      this.subCategory = res.data.result
    },
  }
})